﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using GlxRRSDB;
using System.Data.Sql;

namespace GlxRRSMain
{
    public partial class ConfigurationForm : Form
    {
        public bool isReady = false;
        public ConfigurationForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connectionStringTemplate = "Data Source={0};Initial Catalog=ReportDB;Integrated Security=True";
            string connectionString = String.Format(connectionStringTemplate, cbConnectionString.Text);
            bool rc = ReportDataSet.init(connectionString);
            if (rc)
            {
                MessageBox.Show("Config succeeded.");
                //Map the roaming configuration file. This enables the application to access the configuration file using the 
                //System.Configuration.Configuration class 
                ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
                configFileMap.ExeConfigFilename = "db.config";
                // Get the mapped configuration file. 
                Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
                config.ConnectionStrings.ConnectionStrings["ReportDB"].ConnectionString = connectionString;
                config.Save();
                Close();
                isReady = true;
            }
            else
            {
                MessageBox.Show(connectionString + " NOT work.");
            }
        }

        private void ConfigurationForm_Load(object sender, EventArgs e)
        {
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
            System.Data.DataTable table = instance.GetDataSources();
            foreach (System.Data.DataRow row in table.Rows)
            {
                string instanceName = string.Empty;
                if (row["ServerName"] != DBNull.Value) instanceName = row["ServerName"].ToString();
                if (row["InstanceName"] != DBNull.Value || !string.IsNullOrEmpty(Convert.ToString(row["InstanceName"]).Trim()))
                {
                    instanceName += @"\" + Convert.ToString(row["InstanceName"]).Trim();
                }
                cbConnectionString.Items.Add(instanceName);
                cbConnectionString.Show();
            }
        }
    }
}
